/**********************************************************
FileName: poll.c
Author: Version : Date: Casiawu(wujh@emsyschina.com)
Description: // 网关 模拟 客户端   2018.6.21
1. -------
History: // 历史修改记
<author> <time> <version > <desc>  asasasa
casiawu 2008/2/12 1.0 build this module for linux (2.6.21)
***********************************************************/
#include <stdio.h>
#include <sys/types.h>  
#include <sys/stat.h>    
#include <errno.h>     
#include <string.h>
#include <stdlib.h>  
#include <unistd.h>  
#include <sys/socket.h>
#include <netinet/tcp.h> 
#include <netinet/in.h>
#include <arpa/inet.h>

#include "gateway.h"

typedef struct message{
	int fd;
	unsigned int length;
	char data[128];
}SerData;

int main()
{
	int sockefd;
	int ret;
	int maxfd;
	int confd;
	char buf[128] = {0};
	SerData  rddata = {0};
	fd_set readfs;
	struct timeval timeout={0,100}; 
	
	sockefd = ServerInit("0", 8888);
	if(sockefd < 0){
		printf("ServerInit failed \n");
		return -1;
	}
	printf("ServerInit success \n");
	
	while(1){
		printf("wait for connection \n");
		confd = accept(sockefd,NULL,NULL);//wait answer
		printf("confd = %d \n",confd);
		SetTcpKeepalive(confd, 10, 2, 3);
		maxfd = confd + 1;
		SetNonblockMode(confd);
		
		while(1){
			bzero(&readfs, sizeof(readfs));
			FD_ZERO(&readfs);
			FD_SET(confd, &readfs);
			
			ret = select(maxfd, &readfs, NULL, NULL, NULL);
			if(ret < 0){
				perror("select ");
				break;
			}else{
				if(FD_ISSET(confd,&readfs)){
					bzero(&rddata, sizeof(rddata));
					ret = recv(confd, &rddata, sizeof(rddata), 0);
					if(ret <= 0){
						close(confd);
						break;
					}
					printf("buf:%s,len:%d,fd:%d\n",
							rddata.data, rddata.length, rddata.fd);
					send(confd, &rddata, sizeof(rddata), 0);
				}
			}
		}
	}
}
